package com.wanmao.test.framgent;

import android.app.DatePickerDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wanmao.test.DefectListActivity;
import com.wanmao.test.MainActivity;
import com.wanmao.test.R;
import com.wanmao.test.adapter.InstitutionItemsGridviewAdapter;
import com.wanmao.test.model.InstitutionModel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.wanmao.test.util.DateUtils.dateToStamp;


public class Framgent_Test_Search extends Fragment implements View.OnClickListener {
    private TextView tv_defect;
    private TextView tv_progress;
    private Button btn_search,btn_reset,btn_TimeStart,btn_TimeEnd;
    private String TimeStart,TimeEnd;
    LinearLayout tab_left,LL_XLID;
    RelativeLayout tab_right;
    View mask;
    EditText et_search,et_SBID,et_QXXZ,et_QXZT,et_SBLX,et_BDZID,et_BZID,et_XLID;
    private ExpandableListView mListView;
    private Context my_context;
    private RadioButton radioButton_SD,radioButton_BD;
    private LinearLayout LL_bdShow;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_search, container, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            my_context=getContext();
        }
        intenView(view);
        return view;

    }

    private void intenView(View view) {
        mListView= (ExpandableListView) view.findViewById(R.id.my_lv_list);
        tv_defect = (TextView)view.findViewById(R.id.tv_defect);
        tv_defect.setOnClickListener(this);
        tv_progress = (TextView)view.findViewById(R.id.tv_progress);
        tv_progress.setOnClickListener(this);
        tab_left = (LinearLayout) view.findViewById(R.id.tab_left);
        tab_right = (RelativeLayout) view.findViewById(R.id.tab_right);
        btn_search = (Button) view.findViewById(R.id.btn_search);
        btn_search.setOnClickListener(this);
        btn_reset= (Button) view.findViewById(R.id.btn_reset);
        btn_reset.setOnClickListener(this);
        mask = view.findViewById(R.id.mask);
        et_search =(EditText) view.findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                List<InstitutionModel> result;
                if (TextUtils.isEmpty(s)) {
                    result = institutionInfoList;
                } else {
                    result = new ArrayList<>();
                    for (InstitutionModel m : institutionInfoList) {
                        if (m.getFileName().contains(s.toString()))
                            result.add(m);
                    }
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    TransitionManager.beginDelayedTransition(mListView);
                }
                mListView.setAdapter(new NewSearchAdapter(result,my_context));
            }
        });
        //初始化数据
        initSearchData();

        //
        radioButton_SD= (RadioButton) view.findViewById(R.id.radioButton_SD);
        radioButton_BD= (RadioButton) view.findViewById(R.id.radioButton_BD);

        LL_bdShow = (LinearLayout) view.findViewById(R.id.LL_bdShow);

        radioButton_SD.setChecked(true);
        LL_bdShow.setVisibility(View.GONE);
        radioButton_SD.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    LL_bdShow.setVisibility(View.GONE);
                    LL_XLID.setVisibility(View.VISIBLE);
                }
            }
        });
        radioButton_BD.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    LL_bdShow.setVisibility(View.VISIBLE);
                    LL_XLID.setVisibility(View.GONE);
                    et_XLID.setText("");
                }

            }
        }
        );

        btn_TimeStart=(Button) view.findViewById(R.id.btn_TimeStart);
        btn_TimeEnd=(Button) view.findViewById(R.id.btn_TimeEnd);
        Calendar ca = Calendar.getInstance();
        final int mYear = ca.get(Calendar.YEAR);
        final int mMonth = ca.get(Calendar.MONTH);
        final int mDay = ca.get(Calendar.DAY_OF_MONTH);

        btn_TimeStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(my_context, onDateSetListenerStart, mYear, mMonth, mDay).show();

            }
        });
        btn_TimeEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(my_context, onDateSetListenerEnd, mYear, mMonth, mDay).show();
            }
        });



        et_SBID =(EditText) view.findViewById(R.id.et_SBID);
        et_QXXZ =(EditText) view.findViewById(R.id.et_QXXZ);
        et_QXZT =(EditText) view.findViewById(R.id.et_QXZT);
        et_SBLX =(EditText) view.findViewById(R.id.et_SBLX);
        et_BDZID =(EditText) view.findViewById(R.id.et_BDZID);
        et_BZID =(EditText) view.findViewById(R.id.et_BZID);
        et_XLID =(EditText) view.findViewById(R.id.et_XLID);
        LL_XLID=(LinearLayout) view.findViewById(R.id.LL_XLID);
        et_SBID.setText("");
        et_QXXZ.setText("");
        et_QXZT.setText("");
        et_SBLX.setText("");
        et_BDZID.setText("");
        et_BZID.setText("");
        et_XLID.setText("");
        btn_TimeStart.setText("开始日期");
        btn_TimeEnd.setText("结束日期");
        TimeStart="";
        TimeEnd="";

    }
    private void initSearchData() {
        if (null == institutionInfoList)
            institutionInfoList = new Gson().fromJson(getJsonStr(getActivity(), "biaozhunshuju1.json"), new TypeToken<List<InstitutionModel>>() {
            }.getType());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final NewSearchAdapter adapter = new NewSearchAdapter(institutionInfoList,getContext());
            mListView.setAdapter(adapter);
            mListView.setGroupIndicator(null);
        }
    }
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.img_back) {
        } else if (view.getId() == R.id.tv_defect) {
            tv_defect();
        } else if (view.getId() == R.id.tv_progress) {
            tv_progress();
        } else if (view.getId() == R.id.btn_search) {
            btn_search();
        } else if (view.getId() == R.id.btn_reset) {
            btn_reset();
        }
    }

    private void btn_search() {

        if (!MainActivity.istrue.equals("true")) {
            Toast.makeText(my_context, "请在内网环境下查询", Toast.LENGTH_SHORT).show();
            return;
        }else{
            checkParams();
        }


    }

    private void checkParams(){

        if (radioButton_SD.isChecked()) {
            String type="SD";;
            String SDid=et_SBID.getText().toString().replaceAll(" ", "");
            String XLid=et_XLID.getText().toString().replaceAll(" ", "");
            if(SDid.equals("")&&XLid.equals("")){
                Toast.makeText(my_context, "至少填写一项查询条件", Toast.LENGTH_SHORT).show();
            }else{
                Intent intent = new Intent(getActivity(), DefectListActivity.class);
                intent.putExtra("type", type);
                intent.putExtra("SDid", SDid);
                intent.putExtra("XLid", XLid);
                startActivity(intent);
            }

        } else if (radioButton_BD.isChecked()) {
            String type="BD";;
            String SDid=et_SBID.getText().toString().replaceAll(" ", "");
            String BZid=et_BZID.getText().toString().replaceAll(" ", "");
            String BDZid=et_BDZID.getText().toString().replaceAll(" ", "");
            String SBLX=et_SBLX.getText().toString().replaceAll(" ", "");
            String QXZT=et_QXZT.getText().toString().replaceAll(" ", "");
            String QXXZ=et_QXXZ.getText().toString().replaceAll(" ", "");

            if(SDid.equals("")&&BZid.equals("")&&BDZid.equals("")&&SBLX.equals("")&&QXZT.equals("")&&QXXZ.equals("")&&TimeStart.equals("")&&TimeEnd.equals("")){
                Toast.makeText(my_context, "至少填写一项查询条件", Toast.LENGTH_SHORT).show();
            }else{
                Intent intent = new Intent(getActivity(), DefectListActivity.class);
                intent.putExtra("type", type);
                intent.putExtra("SDid", SDid);
                intent.putExtra("BZid", BZid);
                intent.putExtra("BDZid", BDZid);
                intent.putExtra("SBLX", SBLX);
                intent.putExtra("QXZT", QXZT);
                intent.putExtra("QXXZ", QXXZ);
                intent.putExtra("TimeStart", TimeStart);
                intent.putExtra("TimeEnd", TimeEnd);
                startActivity(intent);
            }

        }

    }
    private void btn_reset() {
        et_SBID.setText("");
        et_QXXZ.setText("");
        et_QXZT.setText("");
        et_SBLX.setText("");
        et_BDZID.setText("");
        et_BZID.setText("");
        et_XLID.setText("");
        btn_TimeStart.setText("开始日期");
        btn_TimeEnd.setText("结束日期");
        TimeStart="";
        TimeEnd="";
    }


    private void tv_defect() {
        tv_defect.setBackgroundResource(R.drawable.round_bg_search_blue);
        tv_defect.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.white));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            tv_progress.setBackground(null);
        }
        tv_progress.setTextColor(Color.parseColor("#808080"));
        tab_left.setVisibility(View.VISIBLE);
        tab_right.setVisibility(View.GONE);
        mask.setVisibility(View.VISIBLE);
    }

    private void tv_progress() {
        tv_progress.setBackgroundResource(R.drawable.round_bg_search_blue);
        tv_progress.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.white));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            tv_defect.setBackground(null);
        }
        tv_defect.setTextColor(Color.parseColor("#808080"));
        tab_right.setVisibility(View.VISIBLE);
        tab_left.setVisibility(View.GONE);
        mask.setVisibility(View.GONE);
    }
    private List<InstitutionModel> institutionInfoList;


    public static String getJsonStr(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    class NewSearchAdapter extends BaseExpandableListAdapter{
        private List<InstitutionModel> list;
        private Context context;

        public NewSearchAdapter(List<InstitutionModel> list,Context context) {
            this.list = list;
            this.context = context;
        }

        @Override
        public int getGroupCount() {
            return list.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return list.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return list.get(groupPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return 1;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            final GroupHolder Gholder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_institution_search_grp, null);
                Gholder = new GroupHolder(convertView);
                convertView.setTag(Gholder);
            } else {
                Gholder = (GroupHolder) convertView.getTag();
            }
            InstitutionModel institutionModel = list.get(groupPosition);
            Log.e("查询", "getGroupView: "+groupPosition+institutionModel.getFileName() );
            Gholder.tv_institution_name.setText(institutionModel.getFileName());
            if (isExpanded) {
                Gholder.img_arrow.setImageResource(R.drawable.common_arrow_up);
            } else {
                Gholder.img_arrow.setImageResource(R.drawable.common_arrow_down);
            }
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ChildHolder Cholder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.item_institution_search_cld, null);
                Cholder = new ChildHolder(convertView);
                convertView.setTag(Cholder);
            } else {
                Cholder = (ChildHolder) convertView.getTag();
            }
            Cholder.gv_items.setAdapter(new InstitutionItemsGridviewAdapter(context, list.get(groupPosition).getFileName(), list.get(groupPosition).getTabs()));
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        class GroupHolder {
            public GroupHolder(View view) {
                tv_institution_name = (TextView) view.findViewById(R.id.tv_institution_name);
                img_arrow = (ImageView) view.findViewById(R.id.img_arrow);
            }
            TextView tv_institution_name;
            ImageView img_arrow;
        }

        class ChildHolder {
            public ChildHolder(View view) {
                gv_items = (GridView)view.findViewById(R.id.gv_items);
            }
            GridView gv_items;
        }
    }


    private DatePickerDialog.OnDateSetListener onDateSetListenerStart = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            int mYear = year;
            int mMonth = monthOfYear;
            int mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            } else {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            }
            TimeStart=dateToStamp(days+" 00:00:00");

            btn_TimeStart.setText(days);
        }
    };

    private DatePickerDialog.OnDateSetListener onDateSetListenerEnd = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            int mYear = year;
            int mMonth = monthOfYear;
            int mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            } else {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            }
            TimeEnd=dateToStamp(days+" 23:59:59");
            btn_TimeEnd.setText(days);
        }
    };


}
